// 导入登录接口
import { loginAPI, getUserProfileAPI, getUserInfoAPI } from '@/api/user'

const state = () => {
  return {
    // 令牌
    token: '',
    // 用户信息
    userInfo: {}
  }
}
const mutations = {
  // 设置token
  setToken: (state, val) => {
    state.token = val
  },
  // 设置用户信息
  setUserInfo: (state, val) => {
    state.userInfo = val
  },
  // 清空token
  removeToken: (state) => {
    state.token = ''
  },
  // 清空userInfo
  removeUserInfo: (state) => {
    state.userInfo = {}
  }
}
const actions = {
  // 登录action
  loginAction: async({ commit }, loginForm) => {
    // 发起登录请求
    const resp = await loginAPI(loginForm)
    // 提交mutation
    commit('setToken', resp.data)
  },

  // 获取用户信息
  getUserInfoAction: async({ commit }) => {
    // 获取用户基本资料，实际上是为了获取id
    const { data: userProfile } = await getUserProfileAPI()
    // 基于此次接口返回的id发起第二次请求获取用户信息
    const { data: userInfo } = await getUserInfoAPI(userProfile.userId)
    commit('setUserInfo', { ...userProfile, ...userInfo })// 两个对象合并后作为参数喜欢给mutation
  },

  // 退出登录action
  logoutAction: ({ commit }) => {
    commit('removeToken')
    commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
